package com.shell.customer.accreditation.rx;

import com.shell.bee.base.utils.StringUtil;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.base.dao.CusExtraDao;
import com.shell.customer.base.dao.CusLvlDao;
import com.shell.customer.base.service.CusLvlService;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.invitation.service.InvtCusService;
import com.shell.customer.po.CusExtra;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusLvl;
import com.shell.customer.po.CusRec;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SetCusLvlSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private InvtCusService invtCusService;
	@Autowired
	private CusLvlService cusLvlService;
	@Autowired
	private CusExtraDao cusExtraDao;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private CusLvlDao cusLvlDao;

	public void onApplicationEvent(AccreditEvent event) {
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();
		List<CusInvt> cusInvts = this.invtCusService.getCusInvtByCusName(cus.getCusName());

		CusExtra cusExtra = (CusExtra) this.cusExtraDao.selectByPrimaryKey(cus.getCusId());
		CusRec invtCus;
		if ((cusExtra != null) && (StringUtil.notEmpty(cusExtra.getInviterCusId()))) {
			invtCus = (CusRec) this.cusRecService.selectByKey(cusExtra.getInviterCusId());
			CusLvl parentLvl = new CusLvl();
			parentLvl.setGrpId(invtCus.getGrpId());
			parentLvl.setCusId(invtCus.getCusId());
			parentLvl = (CusLvl) this.cusLvlDao.selectOne(parentLvl);
			int level = 1;
			if (parentLvl != null) {
				level = parentLvl.getCusLvl().intValue() + 1;
			}
			String grpId = invtCus.getGrpId();

			CusLvl delLvl = new CusLvl();
			delLvl.setGrpId(grpId);
			delLvl.setCusId(cus.getCusId());
			this.cusLvlDao.delete(delLvl);

			CusLvl cusLvl = new CusLvl();
			cusLvl = new CusLvl();
			cusLvl.setGrpId(grpId);
			cusLvl.setCusId(cus.getCusId());
			cusLvl.setCusLvl(Integer.valueOf(level));
			this.cusLvlDao.insert(cusLvl);
		}
		for (CusInvt invt : cusInvts) {
			this.cusLvlService.setCusLvl(invt);
		}
	}
}
